Skip to main content

React : Implementing Server-Side Pagination in React and .NET Core C#

 

Server-side pagination is essential for managing large datasets efficiently in web applications. In this blog post, we'll explore how to implement server-side pagination using React for the frontend and .NET Core for the backend. By fetching data from the server in chunks, we can improve performance and user experience while handling large datasets.
Step 1: Set Up the .NET Core Web API:
Begin by creating a .NET Core Web API project to serve as the backend for our pagination example. Define endpoints to retrieve paginated data from the server.
Create a .NET Core Web API Project:

dotnet new webapi -n PaginationAPI
cd PaginationAPI
Define a Model:
Create a simple model class to represent the data entity.
// DataModel.cs
public class DataModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    // Add more properties as needed
}
an example of setting up a mock repository in a .NET Core Web API project using Entity Framework Core to connect to a SQL database.
Install Entity Framework Core:
Ensure you have Entity Framework Core installed in your project. You can install it via NuGet Package Manager or .NET CLI.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

Set Up DbContext: Create a DbContext class to represent the database context and define a DbSet for your model.

// DataContext.cs
using Microsoft.EntityFrameworkCore;

public class DataContext : DbContext
{
    public DbSet<DataModel> Data { get; set; }

    public DataContext(DbContextOptions<DataContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Configure entity mappings, relationships, etc.
    }
}

Configure Connection String: Update your appsettings.json file to include the connection string for your SQL Server database.

// appsettings.json
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=YourDatabaseName;User=YourUsername;Password=YourPassword;"
  }
}

Register DbContext in Dependency Injection Container: Configure your DbContext in the ConfigureServices method of the Startup class.

// Startup.cs
using Microsoft.EntityFrameworkCore;

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DataContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddScoped<IDataRepository, DataRepository>();
    services.AddControllers();
}

Create Repository Interface: Define an interface for your repository.

// IDataRepository.cs
using System.Collections.Generic;

public interface IDataRepository
{
    IEnumerable<DataModel> GetData();
    // Add more methods as needed
}

Implement Repository Class: Create a repository class that implements the interface and interacts with the DbContext.

// DataRepository.cs
using System.Collections.Generic;
using System.Linq;

public class DataRepository : IDataRepository
{
    private readonly DataContext _context;

    public DataRepository(DataContext context)
    {
        _context = context;
    }

    public IEnumerable<DataModel> GetData()
    {
        return _context.Data.ToList();
    }

    // Implement additional repository methods as needed
}
With these steps, you have set up a mock repository in your .NET Core Web API project using Entity Framework Core to connect to a SQL database. You can now use this repository to interact with your database and perform CRUD operations on your data entities.

Step 2: Implement Server-Side Pagination in .NET Core: Create a controller to handle requests for paginated data.
// DataController.cs
using Microsoft.AspNetCore.Mvc;

[Route("api/[controller]")]
[ApiController]
public class DataController : ControllerBase
{
    private readonly MockRepository _repository;

    public DataController(MockRepository repository)
    {
        _repository = repository;
    }

    [HttpGet]
    public IActionResult GetPaginatedData(int page = 1, int pageSize = 10)
    {
        var data = _repository.GetData();
        var paginatedData = data.Skip((page - 1) * pageSize).Take(pageSize);
        return Ok(paginatedData);
    }
}
Step 3: Set Up React Application: Generate a new React application using Create React App or any other preferred method. This will serve as the frontend for our pagination example.
npx create-react-app pagination-app
cd pagination-app
Step 4: Implement Pagination Component in React: Create a pagination component in React to allow users to navigate through pages and fetch paginated data from the server.
// PaginationComponent.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const PaginationComponent = () => {
  const [data, setData] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);

  useEffect(() => {
    fetchData();
  }, [currentPage]);

  const fetchData = async () => {
    try {
      const response = await axios.get(`/api/data?page=${currentPage}`);
      setData(response.data);
      // Calculate total pages based on response
      setTotalPages(10); // Example: Assuming 10 total pages
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  const goToPage = (page) => {
    setCurrentPage(page);
  };

  return (
    <div>
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
      <div>
        {Array.from({ length: totalPages }).map((_, index) => (
          <button key={index + 1} onClick={() => goToPage(index + 1)}>{index + 1}</button>
        ))}
      </div>
    </div>
  );
};

export default PaginationComponent;
Step 5: Incorporate Pagination Component into App Component: Integrate the pagination component into your main App component to display paginated data in your React application.
// App.js
import React from 'react';
import PaginationComponent from './PaginationComponent';

const App = () => {
  return (
    <div>
      <h1>Pagination Example</h1>
      <PaginationComponent />
    </div>
  );
};

export default App;
Conclusion: By following the steps outlined in this blog post, you can implement server-side pagination in your React and .NET Core web application. Server-side pagination helps optimize performance and manage large datasets efficiently, providing a seamless user experience. With React handling the frontend and .NET Core powering the backend, you can create robust and scalable web applications capable of handling significant amounts of data.

Comments

Popular posts from this blog

Optional Parameters in C# — Writing Flexible and Clean Methods

Hello, .NET developers! 👋 How often have you created multiple method overloads just to handle slightly different cases? Maybe one method accepts two parameters, another three, and one more adds a flag for debugging? That’s a lot of code duplication for something that can be solved beautifully with optional parameters . Optional parameters in C# let you define default values for method arguments. When a caller doesn’t pass a value, the compiler automatically substitutes the default. This feature helps keep your APIs simple, readable, and maintainable. 🎥 Explore more on YouTube : DotNet Full Stack Dev Understanding Optional Parameters Optional parameters are defined by assigning default values in the method signature. When calling the method, you can omit those parameters if you’re okay with the defaults. Example public class Logger { public void Log(string message, string level = "INFO", bool writeToFile = false) ...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...